import { reactive } from '../reactive/main.js'
import { isObject } from '../utils/index.js';

let activeEffect = null;

// 定义副作用函数
export function effect(fn) {
	// 设置当前激活的副作用函数
	activeEffect = fn;
	// 执行副作用函数
	fn();
	// 重置
	activeEffect = null;
}
class RefImpl {
	dep = new Map()
	constructor(value) {
		this.__v_isRef = true;
		this._value = isObject(value) ? reactive(value) : value
	}
	get value() {
		if (activeEffect) this.dep.set(activeEffect, 0)
		return this._value
	}
	set value(val) {
		this._value = isObject(val) ? reactive(val) : val;
		const dep = this.dep;
		for (const effect of dep.keys()) {
			effect()
		}
	}
}

export const ref = (rawValue) => {
	return new RefImpl(rawValue)
}
export function isRef(r) {
	return !!(r && r.__v_isRef === true)
}